import React,{Component} from 'react'
import Dropzone from 'react-dropzone'
import $ from 'jquery'
import { message,Spin } from 'antd';
import {browserHistory} from 'react-router'
import * as pub from '../../config/public'
import * as fetch from '../../config/fetch'
let sub_type = 1;
class SingleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#SingleQuestion' + number).remove();
	}
	render(){
		return(
			<div className="topic-cont SingleQuestion" id={'SingleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text"/><a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input  required="required" type="radio" name={'single_answer'+this.props.number}/>A</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>B</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>C</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class MultipleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#MultipleQuestion' + number).remove();
	}
	render(){
		return(
			<div  className="topic-cont MultipleQuestion" id={'MultipleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text"/><a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input type="checkbox"/>A</label><label>
					<input type="checkbox"/>B</label><label>
					<input type="checkbox"/>C</label><label>
					<input type="checkbox"/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class EditCourse extends Component {
	constructor(props) {
		super(props)
		this.state = {
			videos: [],
			enclosures: [],
			singleNum: 0,
			multipleNum: 0,
			loading: false,
			coursedata: {},
			courseattach: [],
			attachvideo: {},
			titleList: {},
			categoriesList:[],
			course_type:'',
		}
	}
	chooseVideo(accepted, rejected) {
		if(accepted[0].size > 50*1024*1024){
			message.error('视频大小不超过50MB', 3);
			return;
		}
		this.setState({
			videos : accepted
		});
	}
	changeVideo(e) {
		if (e.target.duration / 60 > 5) {
			message.error('视频不超过5分钟', 3);
			this.setState({
				videos: []
			})
		}
	}
	chooseEnclosure(accepted, rejected){
		console.log(accepted,rejected)
		if(accepted.length+this.state.courseattach.length+this.state.enclosures.length> 5){
			message.error('附件不超过5个', 1);
			return;
		}
		for (var i = 0; i < accepted.length; i++) {
			if (accepted[i].size > 10 * 1024 * 1024) {
				message.error("单个文件大小不超过10MB")
				return;
			}
		}
		this.setState({
			enclosures : this.state.enclosures.concat(accepted),
		});
	}
	
//	addSingle() {
		// if(this.state.singleNum + this.state.multipleNum === 5){
		// 	message.error('考题不超过5道', 1);
		// 	return;
		// }
//		this.setState({
//			singleNum: this.state.singleNum + 1
//		})
//	}
//	addMultiple() {
		// if(this.state.singleNum + this.state.multipleNum === 5){
		// 	message.error('考题不超过5道', 1);
		// 	return;
		// }
//		this.setState({
//			multipleNum: this.state.multipleNum + 1
//		})
//	}
	add(e) {
		e.preventDefault();
		let SingleQuestion = [];
		let MultipleQuestion = [];

		$('.SingleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='radio']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			SingleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		$('.MultipleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='checkbox']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			MultipleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		let flag = false;
		for (let x of MultipleQuestion) {
			if (x.answer.length === 0) {
				flag = true;
				break;
			}
		}
		if (flag) {
			message.error('多选题中有答案未选择', 1);
			return;
		}


        if(this.state.coursedata.coursevideoPath===''){
            	 if (this.state.videos.length <= 0) {
                       message.error('请添加课程视频', 1);
			    	   return;
				 }
		}


		let coursedata = {};
		let checkboxTitles = [];
		let radioTitles = [];

		
		coursedata.courseName = $('#course_name').val();;
		coursedata.courseDesc = $('#course_describe').val();;
		coursedata.courseChannel = $('#course_channel').val();
		sub_type === 1 ? coursedata.checkState = '4' : coursedata.checkState = '3'
		coursedata.courseType = this.state.course_type;
		coursedata.courseId=this.props.courseId; 
		if (SingleQuestion.length + MultipleQuestion.length > 0) {
			if ($('#answer_time').val() === '') {
				message.error('请输入答题时间', 2);
				return;
			} else {
				coursedata.answerTime = $('#answer_time').val();
			}

		}
		if(coursedata.checkState==="3"){
			if(SingleQuestion.length + MultipleQuestion.length !== 5){
				message.error('请提交5道考题', 2);
				return;
			}
		}
		


		for (let x of SingleQuestion) {
			radioTitles.push({
				radioTitle: x.question,
				radioAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				radioAnswer: x.answer,
				radioTitleType: 1
			});
		}
		for (let x of MultipleQuestion) {
			checkboxTitles.push({
				checkboxTitle: x.question,
				checkboxAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				checkboxAnswer: x.answer,
				checkboxTitleType: 2
			});
		}

		let formData = new FormData();
		formData.append('radioTitles', JSON.stringify(radioTitles));
		formData.append('coursedata', JSON.stringify(coursedata));
		formData.append('checkboxTitles', JSON.stringify(checkboxTitles));
		if(this.state.videos.length > 0){
			formData.append('video', this.state.videos[0]);
		}else{
             formData.append('video', this.state.coursedata.coursevideoPath);//当视频文件没有改变时
		}
		formData.append('operationType','mainPage');
		formData.append('behaviorDataType','menu');
		formData.append('userCode',JSON.parse(localStorage.getItem('user')).userCode);

       // if(this.state.courseattach.length===0){
			for (let x of this.state.enclosures) {
		    	formData.append('fileList', x);
		     }
		//}else{
            let fileList=[];
		    for (let x of this.state.courseattach) {
			 fileList.push( x.courseattachUniquene);
		     }
             formData.append('filePath',fileList); 
		//}
		pub.loading(this, true);
		
		if (sub_type === 1) {
			fetch.updateCourse(formData).then((data) => {
				if (data.result === 'RC100') {
					message.success(data.errMsg, 2);
					pub.jumpHistory.push('/CourseManage');
				} else {
					message.error(data.errMsg, 3);
				}
				pub.loading(this, false);
			}, (res) => {
				pub.reject(res);
				pub.loading(this, false);
			})
		} else {
			fetch.updateCourse(formData).then((data) => {
//				console.log(data)
				if (data.result === 'RC100') {
					message.success(data.errMsg, 2);
					pub.jumpHistory.push('/CourseManage');
				} else {
					message.error(data.errMsg, 3);
				}
				pub.loading(this, false);
			}, (res) => {
				pub.reject(res);
				pub.loading(this, false);
			})
			 /*fetch.subCourse(formData).then((data) => {
			 	if (data.result === 'RC100') {
			 		message.success('保存成功', 2);
			 		pub.jumpHistory.push('/CourseManage');
			 	} else {
			 		message.error(data.errMsg, 3);
			 	}
			 	pub.loading(this, false);

			 }, (res) => {
			 	pub.reject(res);
			 	pub.loading(this, false);
			 })*/
		}


	}
	componentDidMount() {
		// $('.upload-video').find("input[type='file']").each(function(index, el) {
			// $(this).attr('required', true);
		// });
	}
	componentWillReceiveProps(nextProps) {
	
	}
	componentWillMount() {
		if (localStorage.getItem('user') === null) {
			pub.jumpHistory.push('/Login');
			return;
		}
		// let courseId = this.props.params.id;
		let courseId = this.props.courseId;
		fetch.courseDetail(courseId).then((data) => {
			if (data.result === 'RC100') {
				let single = [],
					multiple = [];
				for (let x of data.titleList) {
					if (x.titleType === '1') {
						single.push(x);
					} else {
						multiple.push(x);
					}
				}
				this.setState({
					coursedata: data.coursedata,
					coursevideoPath:data.coursedata.coursevideoPath,
					courseattach: data.courseattach,
					attachvideo: data.attachvideo,
					titleList: data.titleList,
					singleNum: single.length,
					multipleNum: multiple.length,
					categoriesList:data.categoriesList.categoriesList,
					course_type:data.coursedata.courseType
				}, () => {

					$('#answer_time').val(10);
					$('#course_name').val(data.coursedata.courseName);
					$('#course_describe').val(data.coursedata.courseDesc);
					$('#course_channel').find("option[text=courseChannel]").attr("selected",true);
					// $('#course_type').find("option[text=courseType]").attr("selected",true);
					$('.SingleQuestion').each(function(i) {

						$(this).find('.question').val(single[i].title);
						$(this).find('.describeA').val(single[i].A);
						$(this).find('.describeB').val(single[i].B);
						$(this).find('.describeC').val(single[i].C);
						$(this).find('.describeD').val(single[i].D);


						let answer = pub.getAnswer(single[i].answer);
						$(this).find("input[type='radio']").each((index, el) => {
							for(let x of answer){
								if(x === index){
									el.checked = true;
								}
							}
						})

					})
					
					$('.MultipleQuestion').each(function(i) {

						$(this).find('.question').val(multiple[i].title);
						$(this).find('.describeA').val(multiple[i].A);
						$(this).find('.describeB').val(multiple[i].B);
						$(this).find('.describeC').val(multiple[i].C);
						$(this).find('.describeD').val(multiple[i].D);

						let answer = pub.getAnswer(multiple[i].answer);
						$(this).find("input[type='checkbox']").each((index, el) => {
							for(let x of answer){
								if(x === index){
									el.checked = true;
								}
							}
						})

					})

				})
			} else {
				message.error(data.errMsg, 3);
			}

		}, (response) => {
			pub.reject(response);
		})
	}

	sub(type){
		sub_type = type;
	}
	addSingle() {
		let singleNum = 0,
			multipleNum = 0;
		$('.SingleQuestion').each(function(i) {
			singleNum++;
		})
		$('.MultipleQuestion').each(function(i) {
			multipleNum++;
		})
		if ((singleNum + multipleNum) === 5) {
			message.error('考题不超过5道', 1);
			return;
		}
		this.setState({
			singleNum: this.state.singleNum + 1
		})
	}
	addMultiple() {
		let singleNum = 0,
			multipleNum = 0;
		$('.SingleQuestion').each(function(i) {
			singleNum++;
		})
		$('.MultipleQuestion').each(function(i) {
			multipleNum++;
		})
		if ((singleNum + multipleNum) === 5) {
			message.error('考题不超过5道', 1);
			return;
		}
		this.setState({
			multipleNum: this.state.multipleNum + 1
		})
	}
	DeleteFile(value){
		let file = this.state.enclosures;
		let data = [];
		for(let i in file){
			if(Number(i) !== Number(value)){
				data.push(file[i])
			}
		}
		this.setState({
			enclosures:data
		})
	}
	DeleteFilePH(value){
		let file = this.state.courseattach;
		let data = [];
		for(let i in file){
			if(Number(i) !== Number(value)){
				data.push(file[i])
			}
		}
		this.setState({
			courseattach:data
		})
	}
	render(){
		let course = this.state.coursedata;
		//let coursevideoPath=course.coursevideoPath;
		//console.log(course.coursevideoPath);
		
		
		return(
			<Spin spinning={this.state.loading}>
			<form onSubmit={(e)=>this.add(e)}>
				<div className="panel-120 bg-FFFFFF box-shadow">
					<h3 className="course-title">编辑课程</h3>
					<div className="row">
						{
							this.state.coursevideoPath!==''?
							<div>
								<video 
								//src={this.state.videos[0].preview} 
									src={course.coursevideoPath}
									controls="controls"   
									className = "course_video"
									onCanPlayThrough = {(e)=>this.changeVideo(e)}
									// poster={require('../style/images/test2.png')} 
									preload="auto">
									您的浏览器不支持 video 标签。f
								</video>
								<a className="choose-again" onClick={()=>{this.setState({videos:[],coursevideoPath:''})}}>重新选择视频</a>
							</div>:
							 <div>
								{
									this.state.videos.length > 0 ?		
									<div>		
										<video 
											src={this.state.videos[0].preview} 
											controls="controls"   
											className = "course_video"
											onCanPlayThrough = {(e)=>this.changeVideo(e)}
											// poster={require('../style/images/test2.png')} 
											preload="auto">
											您的浏览器不支持 video 标签。
										</video>
										<a className="choose-again" onClick={()=>{this.setState({videos:[]})}}>重新选择视频</a>
					               </div>:
									<Dropzone
									// maxSize= {31457280}
									multiple={false}
									className='upload-video'
									onDrop={this.chooseVideo.bind(this)}
									accept="video/mp4"
									>
										<div className="file-box">
											<label className="file-label"><i className="icon-upload-alt"></i><span>&nbsp;选择视频</span><p>或将视频拖放到此处</p></label>
											<p>上传格式MP4  时长3~5分钟   ≤50M</p>
											<p>禁止发布的视频内容  视频大小  视频规格  视频时长  高清视频  视频处理流程</p>
										</div>
								   </Dropzone>
						       }
							</div>
						}

						<dl className="info-inp clearFix">
							<dt>课程名称</dt>
							<dd><input type="text" required="required" id="course_name" maxLength="100"/></dd>
						</dl>

						<dl className="info-inp clearFix">
							<dt>课程渠道</dt>
							<dd>
								<select id='course_channel' value={course.courseChannel} disabled="disabled">
								     {pub.courseChannel.map((type,index)=>{
					     		     return(
					     		     	<option key={index} value={index.toString()}>{type}</option>
					     		     	)
					     	            })}
								</select>
							</dd>
						</dl>
						<dl className="info-inp clearFix">
							<dt>课程分类</dt>
							<dd>
								<select id='course_type' value={this.state.course_type} onChange={(e)=>{this.setState({course_type:e.target.value})}} >
								     {this.state.categoriesList.map((item,index)=>{
					     		     return(
					     		     	<option key={index} value={item.code}>{item.name}</option>
					     		     	)
					     	            })}
								</select>
							</dd>
						</dl>


						<dl className="info-inp clearFix">
							<dt>课程描述</dt>
							<dd><textarea required="required" id="course_describe"></textarea></dd>
						</dl>


						<div className="file-box-1">

						    <Dropzone
					         // maxSize= {31457280}
					         className='upload-enclosure'
					         onDrop={this.chooseEnclosure.bind(this)}
							 accept=".xls,.doc,.txt,.pdf,.xlsx,.pptx,.ppt,.docx"
					          >
							<label className="file-label"><i className="icon-upload-alt"></i>上传附件</label>
							</Dropzone>

							<span>（格式：doc/pdf/ppt/xls）</span>
							  <p>
									{
										this.state.enclosures.map((item,index)=>{
										return(
											<span onClick={()=>this.DeleteFile(index)} id={`image${this.props.index}`} key={index}>{item.name}<span  className="trash" style={{color:'red'}}>(删除)</span></span>
											)
								     	})
									}
								{
									this.state.courseattach.map((item,index)=>{
										return(
											<span key={index}><a download={item.courseattachUniquene} href={pub.getFile(item.courseattachUniquene)}>{item.courseAttrachPath}</a><spin onClick={()=>this.DeleteFilePH(index)} id={`image${index}`} style={{color:'red'}}>(删除)</spin></span>
										)
									})
								}
							    </p>
						</div>
				


					</div>
				</div>

				<div className="panel-120 bg-FFFFFF box-shadow">
					<h3 className="course-title">考题信息</h3>

			
				    <div className="time-inp">答题时间
					  <input id='answer_time' type="number"  disabled='true'/>分钟<spin style={{color:'red',marginLeft: '14px'}}>答题时间固定为10分钟</spin>
					</div>
	

					<div className="topic-inp mar-t-20">
						<h4>单项选择题：</h4>
						
						{pub.getObject(this.state.singleNum).map((item,index)=>{
							return(
								  	<SingleQuestion key={index} number={index + 1}/>
								)
						})}

					<a className="add-topic" onClick={()=>this.addSingle()}>
					  <i className="icon-plus-sign-alt"></i>新增一题(单选)
					</a>

                   </div>


					<div className="topic-inp">
						<h4>多项选择题：</h4>
						{pub.getObject(this.state.multipleNum).map((item,index)=>{
							return(
								  	<MultipleQuestion key={index} number={index + 1}/>
								)
						})}
						<a className="add-topic" onClick={()=>this.addMultiple()}>
						  <i className="icon-plus-sign-alt"></i>新增一题(多选)
						</a>
					</div>

					
					<div className="save-subm-btn text-center">
						<div onClick={()=>this.sub(1)} style={{display:"inline-block"}}><button type='submit' value='save' className="btn btn-blue">{this.state.loading?'提交中..':'保存修改'}</button></div>
						<button onClick={()=>this.sub(2)} type='submit'  className="btn btn-blue">{this.state.loading?'提交中..':'提交审核'}</button>
					</div>

			    </div>

			</form>
			</Spin>

			
			)
	}
}

export default EditCourse;